//
//  DBUtil.m
//  YouthOlympic2014
//
//  Created by Li Yuhang on 14-7-3.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "DBUtil.h"
@implementation DBUtil

+(NSString*) databaseLocation{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsPath = paths[0];
    NSString* filePath = [documentsPath stringByAppendingPathComponent:@"yog.db"];
    
    return filePath;
}

+(void) initDatabase{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSString* filePath = [self databaseLocation];
    
    //第一次打开系统时根据数据库模板生成数据库
    if(![fileManager fileExistsAtPath:filePath]){
        FMDatabase* db = [FMDatabase databaseWithPath:[DBUtil databaseLocation]];
        [db open];
        
        [db executeUpdate:@"CREATE TABLE if not exists `messages` (`cid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,`message_type` INTEGER,`title`	VARCHAR(100),`content` VARCHAR(1000),`is_read`	INTEGER,`date`	LONG)"];
        if ([db hadError]){
            NSLog(@"db init error1 %@", [db lastError]);
            return;
        }
        [db executeUpdate:@"CREATE TABLE if not exists `schedule` (`cid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,`item_type` INTEGER,`title`	VARCHAR(100),`place` VARCHAR(100),`icon_type` VARCHAR(20),`start_date` LONG,`add_date` LONG,`ref_id` VARCHAR(100),`day` INTEGER,`date_str` VARCHAR(100),`event_id` VARCHAR(100),`cep_images` VARCHAR(500))"];
    
        if (![db hadError]) {
            NSLog(@"db init error2 %@", [db lastError]);
        }else{
            NSLog(@"db init succ");
        }
        [db close];
    }
    
}

+(FMDatabase*) getDatabase{
    NSString* dbpath = [DBUtil databaseLocation];
    FMDatabase* db =[FMDatabase databaseWithPath:dbpath];
    
    [db open];
    return db;
}

+ (void) initDatabaseByCopyTamplate{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    NSString* filePath = [self databaseLocation];
    
    //第一次打开系统时根据数据库模板生成数据库
    if(![fileManager fileExistsAtPath:filePath]){
        
        NSString* bundlePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"yog.db"];
        NSError* error =nil;
        BOOL success = [fileManager copyItemAtPath:bundlePath toPath:filePath error:&error];
        
        if(success){
            NSLog(@"db init succ");
        }else{
            NSLog(@"db init err %@",error);
        }
    }
}
@end
